package com.agv.backend.service.impl;
import com.agv.backend.entity.AgvResponse;
import com.agv.backend.service.SystemCheckService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Service
@Slf4j
public class SystemCheckServiceImpl implements SystemCheckService {

    private final RestTemplate restTemplate;

    private final DataSource dataSource;

    private static final String BASE_URL = "http://192.168.2.57/prod-api";


    @Autowired
    public SystemCheckServiceImpl(RestTemplate restTemplate, DataSource dataSource) {
        this.restTemplate = restTemplate;
        this.dataSource = dataSource;
    }

    public boolean checkFileSystem() {
        // TODO: 如何检查
        return true;
    }

    public boolean checkDatabaseConnection() {
        try(
                Connection connection = dataSource.getConnection()
        ) {
            return connection.isValid(5);
        } catch (Exception e) {
            return false;
        }
    }

    public boolean checkAgvConnection() {
        String url = BASE_URL + "/system/check/agv";
        ResponseEntity<AgvResponse> result = restTemplate.getForEntity(url, AgvResponse.class);
        log.info("agv {}",result.getBody());
        Boolean data = (Boolean) result.getBody().getData();
        return Boolean.TRUE.equals(data);
    }


    public boolean checkCameraConnection() {
        String url = BASE_URL + "/system/check/cam";
        ResponseEntity<AgvResponse> result = restTemplate.getForEntity(url, AgvResponse.class);
        AgvResponse body = result.getBody();
        log.info("cam: {}", body);

        List<Boolean> booleanList = (List<Boolean>) result.getBody().getData();
        if(booleanList == null || booleanList.isEmpty()) {
            return false;
        }

        for (Boolean o : booleanList) {
            if( o == null || ! o) {
                return false;
            }
        }

        return true;
    }
}